<?php
/**
 * 接口统一授权类
 * @author flaravel
 */
namespace App\Http\Controllers;

use EasyWeChat\Factory;
use Exception;
use App\Http\Requests\MiniRegisterRequest;
use App\Service\UserService;
use App\User;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class AuthController extends Controller
{

    /**
     * 小程序注册登录
     * @param MiniRegisterRequest $request
     * @param UserService $users
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function mpRegister(MiniRegisterRequest $request, UserService $users)
    {
        try{
            $miniProgram = Factory::miniProgram(config('wechat.mini_program.default'));

            $data = $miniProgram->auth->session($request->code);

            if (isset($data['errcode'])) {
                return $this->failed('code不正确或者已过期');
            }
            //用户是否注册过
            $user = $users->checkRegister($data['openid'], 'wx_mini', $data['unionid'] ?? 0);
            $userInfo = json_decode($request->input('rawData'),true);
            if (is_null($user)) {
                $userData = [
                    'wx_mini_openid' => $data['openid'],
                    'session_key'   => $data['session_key'],
                    'wx_unionid'     => $data['unionId'] ?? null,
                    'avatar'         => $userInfo['avatarUrl'],
                    'nickname'       => $userInfo['nickName'],
                    'gender'         => $userInfo['gender'] == 1 ? '男' : '女',
                    'country'        => $userInfo['country'],
                    'province'       => $userInfo['province'],
                    'city'           => $userInfo['city'],
                ];
                $created = User::create($userData);
                if($created)
                {
                    return $this->sendToken($created);
                }
                return $this->failed('授权失败');
            }else{
                $user->session_key = $data['session_key'];
                $user->avatar = $userInfo['avatarUrl'];
                $user->nickname = $userInfo['nickName'];
                $user->save();
                return $this->sendToken($user);
            }
        }catch (Exception $e) {
            Log::error('授权失败:'.$e->getMessage());
            return $this->failed('授权失效');
        }
    }

    // 退出登陆
    public function logout()
    {
        request()->user()->token()->revoke();
        return $this->success('退出成功');
    }

    /**
     * 发放token
     * @param $user
     * @return mixed
     */
    private function sendToken($user)
    {
        $tokenResult = $user->createToken($user->wx_mini_openid);
        $token = $tokenResult->token;
        $token->expires_at = Carbon::now()->addDays(15);
        $token->save();

        return $this->success([
            'user' => $user,
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => strtotime(Carbon::parse($token->expires_at)->toDateTimeString())
        ]);
    }
}
